#include "stack.h"

void Stack::push(int val){
	NodePtr newNode = new StackNode(val);
	if(isEmpty()){
		top = newNode;
		top->next = nullptr;
		return;
	}
	
	newNode->next = top;
	top = newNode;
}

int Stack::pop(){
	if (isEmpty()) {
		std::cout << "Stack is empty, cannot pop." << std::endl;
		return -1;
	}
	
	NodePtr temp = top;
	int value = top->val;
	top = top->next;
	temp->next = nullptr;
	delete temp;
	return value;
}

bool Stack::isEmpty() const{
	return top == nullptr;
}

int Stack::getPeek() const{
	if (isEmpty()) {
		std::cout << "Stack is empty, no value." << std::endl;
		return -1;
	}
	return top->val;
}

int Stack::getSize() const{
	if(isEmpty())
		return -1;
	
	int count = 0;
	NodePtr current = top;
	
	while(current != nullptr){
		++count;
		current = current->next;
	}
	return count;
}

void Stack::clear(){
	while(!isEmpty()){
		pop();
	}
}

bool Stack::checkElements(int value) const{
	NodePtr current = top;
	while(current != nullptr){
		if(current->val == value)
			return true;
		current = current->next;
	}
	return false;
}

Stack Stack::copyStack(const Stack& original){
	Stack tempStack; //临时栈
	Stack copiedStack; //拷贝栈
	
	//将栈中元素移入临时栈
	NodePtr current = original.top;
	while(current != nullptr){
		tempStack.push(current->val);
		current = current->next;
	}
	
	//将临时栈中元素进行拷贝
	while(!tempStack.isEmpty()){
		copiedStack.push(tempStack.pop());
	}
	return copiedStack;
}

void Stack::printStack() const{
	if(isEmpty())
		return;
	
	NodePtr current = top;
	std::cout<<"Stack: ";
	while(current != nullptr){
		std::cout<<current->val<<" ";
		current = current->next;
	}
	std::cout<<std::endl;
}

void Stack::reverse(){
	Stack tempStack;
	
	while(!isEmpty()){
		tempStack.push(pop());
	}
	*this = tempStack;
}

int Stack::searchEelements(int value){
	NodePtr current = top;
	int position = 1;
	
	while(current != nullptr){
		if(current->val == value)
			return position;
		current = current->next;
		++position;
	}
	return -1;
}

